package com.heima.search.service.impl;

import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.dto.UserSearchDTO;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.search.vo.SearchArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {


    @Autowired
    EsService<SearchArticleVO> esService;

    @Value("${file.minio.readPath}")
    private String readPath;

    @Autowired
    ApUserSearchService apUserSearchService;


    @Override
    public void saveArticle(SearchArticleVO article) {
        esService.save(article,"app_info_article");
    }
    @Override
    public void deleteArticle(String articleId) {
        esService.deleteById("app_info_article",articleId);
    }

    /**
     * ES文章分页搜索
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDTO dto) {
        //1 参数检查
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        // **************异步保存搜索记录*************** 首页保存历史记录
        ApUser user = AppThreadLocalUtils.getUser();
        if (dto.getFromIndex() == 0) {
            if (user != null) {
                dto.setEntryId(user.getId());
            }
            apUserSearchService.insert(dto);
        }
        //********************

        //2 查询条件封装
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 关键词 文章标题
        boolQueryBuilder.must(QueryBuilders.matchQuery("title", dto.getSearchWords()));
        // 发布小于最小时间 分页
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime")
                .lt(dto.getMinBehotTime().getTime());
        boolQueryBuilder.filter(rangeQueryBuilder);

        // 设置每页显示记录数
        builder.from(0);
        builder.size(dto.getPageSize());

        // 发布时间排序
        builder.sort("publishTime", SortOrder.DESC);

        // 高亮处理 三要素（高亮字段、高亮前缀、高亮后缀）
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        builder.highlighter(highlightBuilder);

        builder.query(boolQueryBuilder);
        //3 执行查询解析结果
        PageResponseResult pageResponseResult = esService.search(builder, SearchArticleVO.class, "app_info_article");

        //4 封装结果并返回,处理静态文件的前缀
        List<SearchArticleVO> result = (List<SearchArticleVO>) pageResponseResult.getData();
        List<SearchArticleVO> articleVOList = result.stream().map(searchArticleVO -> {
            searchArticleVO.setStaticUrl(readPath + searchArticleVO.getStaticUrl());
            return searchArticleVO;
        }).collect(Collectors.toList());

        return ResponseResult.okResult(articleVOList);
    }

}
